package com.yb.xczx.cloud.auth.filter;

import com.alibaba.fastjson2.JSONObject;
import com.yb.core.constant.RedisKeyConstant;
import com.yb.core.constant.ServletRequestConstant;
import com.yb.core.model.XczxLoginUser;
import com.yb.core.util.StreamUtil;
import com.yb.xczx.cache.manager.api.XczxCacheManager;
import com.yb.xczx.cache.manager.api.XczxStringCacheManager;
import com.yb.xczx.cloud.auth.bean.XczxSysUser;
import com.yb.xczx.cloud.auth.bean.XczxUserPassAuthenticationToken;
import com.yb.xczx.cloud.auth.bean.vo.XczxSysUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/5/18 15:01
 * FileName: XczxUserAuthenticationFilter
 * Description:
 */
@Slf4j
public class XczxUserAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    XczxStringCacheManager xczxStringCacheManager;

    @Autowired
    @Lazy
    JwtDecoder jwtDecoder;

    private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher("/login",
            "POST");

    private static final AntPathRequestMatcher loginPathMatcher=DEFAULT_ANT_PATH_REQUEST_MATCHER;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //如果是登陆请求，则直接获取请求数据，放入request中
        if(loginPathMatcher.matches(request)){
            try {
                String username = request.getParameter("username");
                if(StringUtils.hasText(username)){
                    filterChain.doFilter(request,response);
                    return;
                }
                XczxLoginUser xczxLoginUser = StreamUtil.readAsObject(XczxLoginUser.class, request.getInputStream());
                request.setAttribute(ServletRequestConstant.XCZX_LOGIN_USER,xczxLoginUser);
                filterChain.doFilter(request,response);
            }catch (Exception e){
                filterChain.doFilter(request,response);
            }
            return;
        }


        String accessToken = request.getParameter("access_token");


        //如果带了jwt令牌则直接放过请求
       String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
       if(StringUtils.hasText(authorization)){
           log.info("user oauth2 access_token is present go ahead");
           filterChain.doFilter(request,response);
           return;
       }

        if(!StringUtils.hasText(accessToken)){
            log.info("access_token is not present, so goto the next authenticationfilter");
            filterChain.doFilter(request,response);
            return;
        }

        String result = xczxStringCacheManager.getString(String.format(RedisKeyConstant.LOGIN_USER_DETAIL_KEY, accessToken));

        if(!StringUtils.hasText(result)){
            filterChain.doFilter(request,response);
            return;
        }


        XczxSysUserVo userVo= JSONObject.parseObject(result, XczxSysUserVo.class);
        XczxSysUser xczxSysUser = new XczxSysUser(userVo.getSysUser(), userVo.getAuthorities());

        XczxUserPassAuthenticationToken authenticated = XczxUserPassAuthenticationToken.authenticated(xczxSysUser, xczxSysUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticated);

        filterChain.doFilter(request,response);

    }
}
